package com.fay.mymiaosha.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/3/15 19:49
 * @Version 1.0
 */
@Component
public class ValidatorImpl implements InitializingBean {
    // after initialization invoke afterPropertiesSet method
    // 当这个bean初始化完成之后，执行该回调方法

    // javax.validator  interface规范 不是实现类
    private Validator validator;

    // 实现校验方法并返回校验结果
    public ValidationResult validate(Object bean) {
        ValidationResult result = new ValidationResult();
        // 校验bean，如果这个bean里面有一些参数的规则违背了由validation定义的annotation的话，就会存入返回的Set中
        Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
        // check errors exist or not, if exist then convert to validationResult by iteration
        // 判断是否有错误，如果有错误，将错误都存入返回的结果map中
        if (constraintViolationSet.size() > 0) {
            // has errors
            result.setHasError(true);
            constraintViolationSet.forEach(constraintViolation -> {
                String errMsg = constraintViolation.getMessage();
                String propertyName = constraintViolation.getPropertyPath().toString();
                result.getErrorMsgMap().put(propertyName, errMsg);
            });
        }
        return result;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        // 将hibernate validator 通过工厂的初始化方式使其实例化
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
}
